<?php

namespace app\controller;

use think\facade\Db;
use think\facade\Request;

class Reserve
{
    public function index()
    {
        session_start(); // 开启会话

        try {
            $data = Request::post();
            // 记录接收到的数据
            error_log(print_r($data, true));

            // 检查 reserve_date 和 reserve_time 是否为空
            if (empty($data['reserve_date'])) {
                return json(['code' => 1, 'msg' => '预约日期不能为空']);
            }
            if (empty($data['reserve_time'])) {
                return json(['code' => 1, 'msg' => '预约时间段不能为空']);
            }

            // 检查所选日期和时间段是否已被预定
            $existingReservation = Db::name('cdydpt_reserve')
                ->where('campusname', $data['campusname'])
                ->where('yard_name', $data['yard_name'])
                ->where('reserve_date', $data['reserve_date'])
                ->where('reserve_time', $data['reserve_time'])
                ->find();

            if ($existingReservation) {
                return json(['code' => 1, 'msg' => '该时间段已被预定']); // 返回时间段已被预定信息
            }

            
            // 创建预定
            // $reservationData = [

            //     'campusname' => $data['campusname'],
            //     'yard_name' => $data['yard_name'],
            //     'reserve_date' => $data['reserve_date'],
            //     'reserve_time' => $data['reserve_time'],
            //     'duration' => 1,
            //     'user_id' => $data['userID'],
            // ];
            
            $result = Db::name('cdydpt_reserve')->insert([
                'campusname' => $data['campusname'],
                'yard_name' => $data['yard_name'],
                'reserve_date' => $data['reserve_date'],
                'reserve_time' => $data['reserve_time'],
                'duration' => 1,
                'user_id' => $data['userID'],
            ]);

            return json(['code' => 0, 'msg' => '预定成功']); // 返回预定成功信息
        } catch (\Exception $e) {
            // 记录异常信息
            error_log('Exception: ' . $e->getMessage());
            error_log('Trace: ' . $e->getTraceAsString());
            return json(['code' => 1, 'msg' => '内部服务器错误']); // 返回服务器错误信息
        }
    }
}
